
import { UserDesc } from '@/store/user';
import { platform } from '@/utils/platform';
import { userWeapp } from './user-weapp';
import { userAlipay } from './user-alipay';
export namespace userApi {
	/**
	* 用在页面登录时调用，用于获取token
	*/
	export const login = async () : Promise<string> => {
		try {
			if (platform.isWeapp()) {
				const token = await userWeapp.login();
				_getUserInfoAsync();
				return Promise.resolve(token);
			}
			if (platform.isAlipay()) {
				const token = await userAlipay.login();
				_getUserInfoAsync();
				return Promise.resolve(token);
			}
			if (platform.isH5()) {
				return Promise.resolve('');
			}
			return Promise.reject(platform.ERROR_PLATFORM);
		} catch (error) {
			return Promise.reject(error);
		}
	}
	const _getUserInfoAsync = async () => {
		// const res = await webAPIs.v1.user.getUserInfo.call();
		// userStore.setUserInfo(res.data);
	}

	export const bindMobile = async (detail : any) : Promise<string> => {
		try {
			console.log('授权', detail);
			if (platform.isWeapp()) {
				const { code } = detail;
				const mobile = await userWeapp.bindMobile(code);
				// const userInfo = { ...userStore.userInfo, mobile: mobile };
				// await userWeapp.updateUser(userInfo);
				_getUserInfoAsync();
				return Promise.resolve(mobile);
			}
			if (platform.isAlipay()) {
				const mobile = await userAlipay.bindMobile();
				// const userInfo = { ...userStore.userInfo, mobile: mobile };
				// await userAlipay.updateUser(userInfo);
				_getUserInfoAsync();
				return Promise.resolve(mobile);
			}
			if (platform.isH5()) {
				return Promise.reject('h5不支持获取手机号');
			}
			return Promise.reject(platform.ERROR_PLATFORM);
		} catch (e) {
			return Promise.reject(e);
		}
	}
	//获取用户头像、昵称,只能在button按下触发
	export const getUserDescAsync = async () : Promise<UserDesc> => {
		try {
			if (platform.isWeapp()) {
				return Promise.reject('请使用微信填写能力');
			}
			if (platform.isAlipay()) {
				const userDesc = await userAlipay.getUserProfile();
				// userStore.setUserDesc(userDesc);
				return Promise.resolve(userDesc);
			}
			return Promise.reject(platform.ERROR_PLATFORM);
		} catch (e) {
			return Promise.reject(e);
		}
	}
	const _delay = async (milliseconds : number) => {
		return new Promise((resolve) => {
			setTimeout(() => {
				resolve('')
			}, milliseconds);
		})
	}
	/**
	 * 退出登录
	 */
	export const loginExit = async () => {
		// userStore.clearToken();
		// userStore.setUserInfo({});
		uni.clearStorageSync();
		return Promise.resolve();
	}
}